package com.model;

import com.alibaba.fastjson.JSON;

public class Threadhelper {
	
	public boolean compareThreadname(String name){
		
		ThreadGroup group = Thread.currentThread().getThreadGroup();
	    ThreadGroup topGroup = group;
	 
	    /* 遍历线程组树，获取根线程组 */
	    while ( group != null )
	    {
	        topGroup    = group;
	        group        = group.getParent();
	    }
	    /* 激活的线程数加倍 */
	    int estimatedSize = topGroup.activeCount() * 2;
	    Thread[] slackList = new Thread[estimatedSize];
	 
	    /* 获取根线程组的所有线程 */
	    int actualSize = topGroup.enumerate( slackList );
	    /* copy into a list that is the exact size */
	    Thread[] list = new Thread[actualSize];
	    System.arraycopy( slackList, 0, list, 0, actualSize );
	    
	    boolean rslt=false;
	    for(int i=0;i<list.length;i++){
	    	if(name.equals(list[i].getName())){
	    		rslt=true;break;
	    	}
	    }
		
	    return rslt;
	}
	
	@SuppressWarnings("deprecation")
	public boolean stopByThredname(String name){
		
		ThreadGroup group = Thread.currentThread().getThreadGroup();
	    ThreadGroup topGroup = group;
	 
	    /* 遍历线程组树，获取根线程组 */
	    while ( group != null )
	    {
	        topGroup    = group;
	        group        = group.getParent();
	    }
	    /* 激活的线程数加倍 */
	    int estimatedSize = topGroup.activeCount() * 2;
	    Thread[] slackList = new Thread[estimatedSize];
	 
	    /* 获取根线程组的所有线程 */
	    int actualSize = topGroup.enumerate( slackList );
	    /* copy into a list that is the exact size */
	    Thread[] list = new Thread[actualSize];
	    System.arraycopy( slackList, 0, list, 0, actualSize );
	    
	    boolean rslt=false;
	    for(int i=0;i<list.length;i++){
	    	if(name.equals(list[i].getName())){
	    		list[i].stop();
	    		rslt=true;break;
	    	}
	    }
		
	    return rslt;
	}
	
	public String getallthrd(){
		
		ThreadGroup group = Thread.currentThread().getThreadGroup();
	    ThreadGroup topGroup = group;
	 
	    /* 遍历线程组树，获取根线程组 */
	    while ( group != null )
	    {
	        topGroup    = group;
	        group        = group.getParent();
	    }
	    /* 激活的线程数加倍 */
	    int estimatedSize = topGroup.activeCount() * 2;
	    Thread[] slackList = new Thread[estimatedSize];
	 
	    /* 获取根线程组的所有线程 */
	    int actualSize = topGroup.enumerate( slackList );
	    /* copy into a list that is the exact size */
	    Thread[] list = new Thread[actualSize];
	    System.arraycopy( slackList, 0, list, 0, actualSize );
	    
	    		
	    return JSON.toJSONString(list);
	}
	
}
